import React, { useState, useEffect } from 'react';
import { IStudent } from '../../types';
import styles from './StudentModal.module.css';

interface StudentModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (student: Omit<IStudent, 'id'> | { id: string } & Partial<IStudent>) => void;
  student?: IStudent | null;
}

const StudentModal: React.FC<StudentModalProps> = ({ isOpen, onClose, onSubmit, student }) => {
  const [name, setName] = useState('');
  const [gender, setGender] = useState<'男' | '女'>('男');
  const [studentId, setStudentId] = useState('');
  const [grade, setGrade] = useState('');
  const [classValue, setClassValue] = useState('');
  const [errors, setErrors] = useState<Record<string, string>>({});

  // 当模态框打开或学生数据变化时，更新表单字段
  useEffect(() => {
    if (student) {
      setName(student.name);
      setGender(student.gender);
      setStudentId(student.studentId);
      setGrade(student.grade || '');
      setClassValue(student.class || '');
    } else {
      // 重置表单
      setName('');
      setGender('男');
      setStudentId('');
      setGrade('');
      setClassValue('');
      setErrors({});
    }
  }, [student, isOpen]);

  // 验证表单
  const validate = () => {
    const newErrors: Record<string, string> = {};
    
    if (!name.trim()) {
      newErrors.name = '姓名不能为空';
    }
    
    if (!studentId.trim()) {
      newErrors.studentId = '学号不能为空';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validate()) {
      return;
    }
    
    if (student) {
      // 编辑模式
      onSubmit({
        id: student.id,
        name,
        gender,
        studentId,
        grade: grade || undefined,
        class: classValue || undefined
      });
    } else {
      // 新增模式
      onSubmit({
        name,
        gender,
        studentId,
        grade: grade || undefined,
        class: classValue || undefined
      });
    }
    
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
        <div className={styles.modalHeader}>
          <h2 className={styles.modalTitle}>
            {student ? '编辑学生信息' : '新增学生'}
          </h2>
          <button className={styles.closeButton} onClick={onClose}>
            &times;
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className={styles.modalBody}>
            <div className={styles.formGroup}>
              <label htmlFor="name">姓名 *</label>
              <input
                type="text"
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="请输入学生姓名"
              />
              {errors.name && <div className={styles.error}>{errors.name}</div>}
            </div>
            
            <div className={styles.formGroup}>
              <label htmlFor="gender">性别</label>
              <select
                id="gender"
                value={gender}
                onChange={(e) => setGender(e.target.value as '男' | '女')}
              >
                <option value="男">男</option>
                <option value="女">女</option>
              </select>
            </div>
            
            <div className={styles.formGroup}>
              <label htmlFor="studentId">学号 *</label>
              <input
                type="text"
                id="studentId"
                value={studentId}
                onChange={(e) => setStudentId(e.target.value)}
                placeholder="请输入学号"
              />
              {errors.studentId && <div className={styles.error}>{errors.studentId}</div>}
            </div>
            
            <div className={styles.formGroup}>
              <label htmlFor="grade">年级</label>
              <input
                type="text"
                id="grade"
                value={grade}
                onChange={(e) => setGrade(e.target.value)}
                placeholder="请输入年级"
              />
            </div>
            
            <div className={styles.formGroup}>
              <label htmlFor="class">班级</label>
              <input
                type="text"
                id="class"
                value={classValue}
                onChange={(e) => setClassValue(e.target.value)}
                placeholder="请输入班级"
              />
            </div>
          </div>
          <div className={styles.modalFooter}>
            <button 
              type="button" 
              className={`${styles.button} ${styles.cancelButton}`}
              onClick={onClose}
            >
              取消
            </button>
            <button 
              type="submit" 
              className={`${styles.button} ${styles.submitButton}`}
            >
              {student ? '更新' : '添加'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default StudentModal;